% exceltoifiles.m  
%
% Excel to individual files 
%
% Loads and excel spreadsheet 
% Looks for non-missing values in each 
% series and 
% Saves each series in the same subdirectory
% With a name matching first row of the spreadsheet 
%
% All series must have all observations 

% matype=1 
% Saves a matfile data.mat with two elements 
% dat data 
% cal calendar vector 

% Inputs 
% ========
clear all; 
close all; 
fname='cn_EVIEWS_DETRENDED';               % File name Where data stored 
bpath='C:\ESTDSGE\DATA\CN';        % Path weher to store files 
s0=1981.25;                      % Starting Date  
s1=2003.5;                      % Ending Date 
freq='Q';                       % Frequency 
matype=1;                       % =0 Save files as  ascii tabs with the name fname matching first row of the spreadsheet 
                                % =1 saves a mat file 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                   END INPUTS                   %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Load Data
cuc=cd; 
cd(bpath); 
[datm,sernam]=xlsread(fname); 
cvec=datm(:,1);
cd(cuc); 

y=datm(:,2:end);
yname=sernam(2:end); 
clear datm sernam; 

[T,n]=size(y); 

cvec2=calvec(s0,s1,freq); 
if any(cvec-cvec2 ~= 0) == 1; 
    error('Check Sample Dates'); 
end; 
clear cvec2; 
ch=[cvec(1);cvec(end);]; 

cuc=cd;
jj=1; 
for jj=1:n; 
    [dat,cal]=cmiss(y(:,jj) , cvec);
    ch2=[cal(1);cal(end)];
    fname=yname{jj}; 
    if sum( ch == ch2 ) ~=2; 
        fpraid(['Missing Observations in ',fname]); 
        error('Missing Data'); 
    end; 
    
    fpraid('e'); 
    fpraid([' Files will be saved as: ',fname] );
    cd(bpath); 
    if matype == 0         
        save(fname,'dat','-ascii','-tabs');
    elseif matype == 1; 
        %fpraid('Warning! You are not saving files individually'); 
        save(fname,'dat','cal');  
    end 
    cd(cuc); 
end